package com.nulldev.util.data.Arrays.arrays;

import java.util.Comparator;
import java.util.List;

import com.nulldev.util.data.Variables;
import com.nulldev.util.internal.backport.arrays.BackportList;
import com.nulldev.util.internal.backport.concurrency9.Lists;

public class MultiComparator<T> implements Comparator<T> {
	private final List<Comparator<? super T>> comparators;

	public MultiComparator(final List<Comparator<? super T>> comparators) {
		this.comparators = comparators;
	}

	@SafeVarargs
	public MultiComparator(final Comparator<? super T>... comparators) {
		this(Lists.of(comparators));
	}

	public int compare(final T o1, final T o2) {
		if (this.comparators.isEmpty())
			return 0;
		else if (this.comparators.size() == 1)
			return this.comparators.get(0).compare(o1, o2);
		else {
			for (final Comparator<? super T> c : this.comparators) {
				final int result = c.compare(o1, o2);
				if (result != 0) {
					return result;
				}
			}
			return 0;
		}
	}

	@SafeVarargs
	public static <T> void sort(final List<T> list, final Comparator<? super T>... comparators) {
		BackportList.sort(list, new MultiComparator<T>(comparators));
	}

	@SafeVarargs
	public static <T> void sort(final ConcurrentList<T> list, final Comparator<? super T>... comparators) {
		Variables.notNullE(list);
		list.navSort(new MultiComparator<T>(comparators));
	}
}